const net = require('net')
const constants = require('./constants')
const messageManage = require('./messageManage')

const serverMapping = {};

class TCPConnectionSocket {

    constructor(socket) {
        this.socket = socket;
        const remoteAddress = socket.remoteAddress;
        let arr = remoteAddress.split(':');
        const remoteIp = arr[arr.length - 1];
        this.remoteIp = remoteIp;
        const remotePort = socket.remotePort;
        this.remotePort = remotePort;
        console.log(`socket connect remoteIp: ${remoteIp}, remote port: ${remotePort}`);
    }

    sendNew() {
        this.socket.write(constants.MESSAGE_NEW);
    }

    /**
     * 发送消息
     * @param msg
     */
    sendMessage(msg) {
        const remoteIp = this.remoteIp;
        const remotePort = this.remotePort;
        console.log(`socket connect remoteIp: ${remoteIp}, remote port: ${remotePort}`);
        this.socket.write(msg);
    }
}

class TCPServer {

    constructor(port, onData) {

        // 初始化TCP收到数据的执行函数
        this.onData = function(socket, data) {
            console.warn('你可能还没有定义数据接收的操作', socket.toString(), data);
        };

        // 定义服务器接收到数据时的操作
        if (onData) {
            this.onData = onData;
        }

        const server = net.createServer( (socket) => {
            // 新的连接
            socket.on('data',(data)=> {
                this.onData(data, socket);
            })
            socket.on('end', (data) => {
                console.log('连接断开')
            })
        });
        this.server = server;

        // 监听客户端的连接
        server.on('connection', (socket) => {
            if (!this.connectedSocketList) {
                this.connectedSocketList = [];
            }
            this.connectedSocketList.push(new TCPConnectionSocket(socket));
            socket.write(`server connected. port: ${port}`);
        });

        this.server = server;
        this.port = port;
    }

    start() {
        // 监听方式
        this.server.listen(this.port, function() {
            console.log('server started!');
        })
    }

    close() {
        this.server.close();
    }

    getMessageList() {
        return messageManage.getList();
    }

    addMessage(message) {
        messageManage.addMessage(message);
        this.sendNew();
    }

    sendNew() {
        if (this.connectedSocketList) {
            for(const socket of this.connectedSocketList) {
                socket.sendNew();
            }
        }
    }
}

module.exports = {
    create(port, onData) {
        const server = new TCPServer(port, onData);
        serverMapping[port] = server;
        return server;
    },
    getByPort(port) {
        return serverMapping[port];
    }
}